﻿using Drive.LiveExcelHost.Controllers;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Text;
using System.Threading.Tasks;

namespace Drive.LiveExcelHost.Services
{
    /// <summary>
    /// 客服端消息收发
    /// </summary>
    public class AgentMessenger : SocketIOService
    {
        AgentChatController controller = new AgentChatController();
        public AgentMessenger(Request request, WebSocketSession session) : base(request, session)
        {
        }

        public override Task OnMessageReceived(string type, string content)
        {
            var agentId = (int)this.session.VisitorId;
            controller.HandleAgentMessage(agentId,0, content);
            return Task.CompletedTask;
        }

        internal async override Task OnSocketIoSessionCreate()
        {
            await RedisPubSub.Subscribe(this.session.RedisChannel, this.session.PushToClient); //私信
            var sessionCount = RedisWebSocketSession.Increase(this.session.RedisChannel);

            RedisAgentStatus.SetStatusOnline(this.session.VisitorId, true);

            var sessionReady =TypedMessage.CreateSessionReady(session.GetBuddy(), new
            {
                sessionCount = sessionCount
            });
            this.session.PushToClient(this.session.SessionId, sessionReady);
        }

        internal async override Task OnSocketIoSessionDestory()
        {
            await RedisPubSub.Unsubscribe("None", this.session.PushToClient); //大厅消息
            await RedisPubSub.Unsubscribe(this.session.RedisChannel, this.session.PushToClient); //私信

            var sessionCount = RedisWebSocketSession.Decrease(this.session.RedisChannel);
            RedisAgentStatus.SetStatusOnline(this.session.VisitorId, sessionCount > 0);
            if (sessionCount == 0)
            {
                await RedisPubSub.Publish("None",TypedMessage.CreateBuddyLeave(session.GetBuddy(), new { }));
            }
        }
        public override void Dispose()
        {
            this.controller.Dispose();
        }
    }
}
